import { Controller } from 'egg';
import AddRoleRule from '../validate/addRoleRule';

export default class HomeController extends Controller {
  // 获取所有角色
  public async allRoles() {
    const { ctx } = this;
    try {
      const roles = await ctx.service.roles.getAllRoles();
      ctx.success(roles);
    } catch (e) {
      ctx.error(500, e.message);
    }
  }
  // 获取单个角色信息
  public async getRoleInfo() {
    const { ctx } = this;
    const { id } = ctx.params;
    try {
      const role = await ctx.service.roles.getRoleInfo(id);
      ctx.success(role);
    } catch (e) {
      ctx.error(400, e.message);
    }
  }
  // 获取所有角色(带参数条件)
  public async index() {
    const { ctx } = this;
    try {
      // get请求 ctx.query
      const roles = await ctx.service.roles.getRolesList(ctx.query);
      ctx.success(roles);
    } catch (e) {
      ctx.error(500, e.message);
    }
  }

  // 新增
  public async create() {
    const { ctx } = this;
    const data = ctx.request.body;
    // console.log(data);
    try {
      // 校验数据
      ctx.validate(AddRoleRule, data);
      const role = await ctx.service.roles.createRoles(data);
      ctx.success(role);
    } catch (e) {
      if (e.errors) {
        ctx.error(400, e.errors);
      } else {
        ctx.error(400, e.message);
      }
    }
  }
  //   // 删除
  public async destroy() {
    const { ctx } = this;
    const { id } = ctx.params;
    try {
      const role = await ctx.service.roles.destroyRole(id);
      ctx.success(role);
    } catch (e) {
      ctx.error(400, e.message);
    }
  }
  // 编辑
  public async update() {
    const { ctx } = this;
    const obj = ctx.request.body;
    const { id } = ctx.params;
    try {
      const role = await ctx.service.roles.updateRole(id, obj);
      ctx.success(role);
    } catch (e) {
      if (e.errors) {
        ctx.error(400, e.errors);
      } else {
        ctx.error(400, e.message);
      }
    }
  }
}
